
package io.zhifei.modules.sys.system.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.zhifei.common.exception.RRException;
import io.zhifei.common.utils.PageUtils;
import io.zhifei.modules.sys.dataStatistical.entity.FollowerChooseInfo;
import io.zhifei.modules.sys.dataStatistical.util.UserFunction;
import io.zhifei.modules.sys.system.dao.SysUserDao;
import io.zhifei.modules.sys.system.entity.SysUserEntity;
import io.zhifei.modules.sys.system.entity.user.MenuButton;
import io.zhifei.modules.sys.system.entity.user.MenuInfoResult;
import io.zhifei.modules.sys.system.entity.user.Meta;
import io.zhifei.modules.sys.system.service.SysRoleService;
import io.zhifei.modules.sys.system.service.SysUserRoleService;
import io.zhifei.modules.sys.system.service.SysUserService;
import io.zhifei.modules.sys.system.util.UserToTree;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;



    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String keyWord = (String) params.get("keyWord");
        String orgId = params.get("orgId").toString();
        Integer page = Integer.valueOf(params.get("page").toString());
        Integer pageSize = Integer.valueOf(params.get("pageSize").toString());
        //查询所有用户
        Page pageParams = new Page(page, pageSize);
        Page<Map<String, Object>> pageResult = sysUserDao.getUserList(pageParams, keyWord, orgId);
        return new PageUtils(pageResult);
    }


    @Override
    public List<String> queryAllPerms(Long userId) {
        return baseMapper.queryAllPerms(userId);
    }

    @Override
    public List<Long> queryRoleList(Long userId) {
        return baseMapper.queryRoleList(userId);
    }

    @Override
    public List<Long> queryAllMenuId(Long userId) {
        return baseMapper.queryAllMenuId(userId);
    }

    @Override
    public SysUserEntity queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }

    @Override
    @Transactional
    public void saveUser(SysUserEntity user,SysUserEntity sysUserEntity) {
        user.setCreateTime(new Date());
        //sha256加密
        user.setPassword(new Sha256Hash(user.getPassword()).toString());
        this.save(user);

        //检查角色是否越权
        checkRole(user,sysUserEntity);

        //保存用户与角色关系
        sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
    }

    @Override
    @Transactional
    public void update(SysUserEntity user,SysUserEntity sysUserEntity) {
        if (StringUtils.isBlank(user.getPassword())) {
            user.setPassword(null);
        } else {
            user.setPassword(new Sha256Hash(user.getPassword()).toString());
        }
        this.updateById(user);

        //检查角色是否越权
        checkRole(user,sysUserEntity);

        if (null !=user.getRoleIdList()){
            //保存用户与角色关系
            sysUserRoleService.saveOrUpdate(user.getUserId(), user.getRoleIdList());
        }

    }

    @Override
    public void deleteBatch(Long[] userId) {
        this.removeByIds(Arrays.asList(userId));
    }

    @Override
    public boolean updatePassword(Long userId, String password, String newPassword) {
        SysUserEntity userEntity = new SysUserEntity();
        userEntity.setPassword(newPassword);
        return this.update(userEntity,
                new QueryWrapper<SysUserEntity>().eq("user_id", userId).eq("password", password));
    }

    @Override
    public List<Map<String, Object>> getUserList() {
        return sysUserDao.userList();
    }

    @Override
    public Object getMenuInfo(Long userId) {
        //用来存放系统管理模块
        List<MenuInfoResult> sysMenuInfo = new ArrayList<>();
        //用来存放业务模块
        List<MenuInfoResult> busMenuInfo = new ArrayList<>();
        //用来存放教务模块
        List<MenuInfoResult> eduMenuInfo = new ArrayList<>();
        //查询出所有数据
        List<MenuInfoResult> list = sysUserDao.getMenuInfo(userId);
        if (list == null || list.size() == 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("sysMenuInfo", sysMenuInfo);
            map.put("busMenuInfo", busMenuInfo);
            map.put("eduMenuInfo", eduMenuInfo);
            return map;
        }
        //将所有数据转为树状图
        List<MenuInfoResult> listToTree = UserToTree.listToTree(list);
        //遍历树状图
        for (MenuInfoResult menuInfoResult : listToTree) {
            if (null == menuInfoResult.getPath()){
                menuInfoResult.setPath("");
            }
            //判断是该目录是哪个模块的
            if (menuInfoResult.getCode().equals("1") && menuInfoResult.getChildren() != null) {
                //处理第一个孩子的数据
                for (MenuInfoResult menuInfoResult1 : menuInfoResult.getChildren()) {
                    if (null == menuInfoResult1.getPath()){
                        menuInfoResult1.setPath("");
                    }
                    //存放所有按钮
                    List<MenuButton> menuButtons = new ArrayList<>();
                    if (menuInfoResult1.getChildren() != null) {
                        //处理第二个孩子的数据
                        for (MenuInfoResult menuInforesult2 : menuInfoResult1.getChildren()) {
                            if (null == menuInforesult2.getPath()){
                                menuInforesult2.setPath("");
                            }
                            MenuButton menuButton = new MenuButton();
                            menuButton.setId(menuInforesult2.getId().toString());
                            menuButton.setTitle(menuInforesult2.getTitle());
                            menuButtons.add(menuButton);
                            menuInforesult2.setChildren(new ArrayList<>());
                        }
                    }
                    Meta meta = menuInfoResult1.getMeta();
                    meta.setRoot(menuButtons);
                }
                sysMenuInfo.add(menuInfoResult);
            } else if (menuInfoResult.getCode().equals("2") && menuInfoResult.getChildren() != null) {
                for (MenuInfoResult menuInfoResult1 : menuInfoResult.getChildren()) {
                    if (null == menuInfoResult1.getPath()){
                        menuInfoResult1.setPath("");
                    }
                    List<MenuButton> menuButtons = new ArrayList<>();
                    if (menuInfoResult1.getChildren() != null) {
                        for (MenuInfoResult menuInforesult2 : menuInfoResult1.getChildren()) {
                            if (null == menuInforesult2.getPath()){
                                menuInforesult2.setPath("");
                            }
                            MenuButton menuButton = new MenuButton();
                            menuButton.setId(menuInforesult2.getId().toString());
                            menuButton.setTitle(menuInforesult2.getTitle());
                            menuButtons.add(menuButton);
                        }
                    }
                    Meta meta = menuInfoResult1.getMeta();
                    meta.setRoot(menuButtons);
                }
                busMenuInfo.add(menuInfoResult);
            } else if (menuInfoResult.getCode().equals("3") && menuInfoResult.getChildren() != null) {
                for (MenuInfoResult menuInfoResult1 : menuInfoResult.getChildren()) {
                    if (null == menuInfoResult1.getPath()){
                        menuInfoResult1.setPath("");
                    }
                    List<MenuButton> menuButtons = new ArrayList<>();
                    if (menuInfoResult1.getChildren() != null) {
                        for (MenuInfoResult menuInforesult2 : menuInfoResult1.getChildren()) {
                            if (null == menuInforesult2.getPath()){
                                menuInforesult2.setPath("");
                            }
                            MenuButton menuButton = new MenuButton();
                            menuButton.setId(menuInforesult2.getId().toString());
                            menuButton.setTitle(menuInforesult2.getTitle());
                            menuButtons.add(menuButton);
                        }
                    }
                    Meta meta = menuInfoResult1.getMeta();
                    meta.setRoot(menuButtons);
                }
                eduMenuInfo.add(menuInfoResult);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("sysMenuInfo", sysMenuInfo);
        map.put("busMenuInfo", busMenuInfo);
        map.put("eduMenuInfo", eduMenuInfo);
        return map;
    }

    /**
     * 检查角色是否越权
     */
    private void checkRole(SysUserEntity user,SysUserEntity sysUserEntity) {
        if (user.getRoleIdList() == null || user.getRoleIdList().size() == 0) {
            return;
        }
        //如果不是超级管理员，则需要判断用户的角色是否自己创建
        //if (user.getCreateUserId() == Constant.SUPER_ADMIN) {
        //    return;
        //}

        ////查询用户创建的角色列表
        //List<Long> roleIdList = sysRoleService.queryRoleIdList(user.getCreateUserId());
        //List<Long> roleLists = new ArrayList<>();
        //roleLists = user.getRoleIdList();
        ////判断是否越权
        //if (!roleIdList.containsAll(roleLists)) {
        //    throw new RRException("不能更改超级管理员所设置的权限");
        //}
        FollowerChooseInfo followerChooseInfo = UserFunction.dataStatisticalByFollower(sysUserEntity);
        if (followerChooseInfo.getManagement() == 0 && followerChooseInfo.getCampus() == 0 && followerChooseInfo.getAllCampus() == 0) {
                throw new RRException("不能更改超级管理员所设置的权限");
        }
    }

    @Override
    @SentinelResource(value = "sayHello")
    public String sayHello(String name) {
        return "hello,"+name;
    }
}